﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using System.Threading.Tasks;
using Windows.Devices.Geolocation;
using System.Threading;
using Windows.UI.Core;


namespace GPSSample
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainPage : Page
    {

        private Geolocator _geolocator = null;
        private CancellationTokenSource _cts = null;
        
        public MainPage()
        {
            this.InitializeComponent();

            _geolocator = new Geolocator();
            //DesiredAccuracy will force the api to select most accurate method, which will be external or built-in gps
            _geolocator.DesiredAccuracy = PositionAccuracy.High;

        }


        private void StartTracking(object sender, RoutedEventArgs e)
        {
            _geolocator.PositionChanged += new TypedEventHandler<Geolocator, PositionChangedEventArgs>(OnPositionChanged);
         }
   
        async private void OnPositionChanged(Geolocator sender, PositionChangedEventArgs e)
        {

            await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                Geoposition pos = e.Position;
                lbStatus.Items.Add("position Changed to Lat: " + pos.Coordinate.Latitude.ToString()  + " long " +pos.Coordinate.Longitude.ToString() );
                txtlati.Text = pos.Coordinate.Latitude.ToString();
                txtlongi.Text = pos.Coordinate.Longitude.ToString();
                txtAlti.Text = pos.Coordinate.Altitude.ToString();
                txtAccuracy.Text = pos.Coordinate.Accuracy.ToString();
                txtSpeed.Text = pos.Coordinate.Speed.ToString();
                txtTime.Text = pos.Coordinate.Timestamp.ToString();
                txtAltiAccu.Text = pos.Coordinate.AltitudeAccuracy.ToString();
                txtHeading.Text = pos.Coordinate.Heading.ToString();
                txtCity.Text = pos.CivicAddress.City.ToString();
                txtPostalCode.Text = pos.CivicAddress.PostalCode.ToString();
                txtState.Text = pos.CivicAddress.State.ToString();
                txtCountry.Text = pos.CivicAddress.Country.ToString();

            });
        }
        
        async private void GetGeolocation(object sender, RoutedEventArgs e)
        {
         
            try
            {
                _cts = new CancellationTokenSource();
                CancellationToken token = _cts.Token;
                Geoposition pos = await _geolocator.GetGeopositionAsync().AsTask(token);
                lbStatus.Items.Add("position Changed to Lat:" + pos.Coordinate.Latitude.ToString() + " long " + pos.Coordinate.Longitude.ToString());
                txtlati.Text = pos.Coordinate.Latitude.ToString();
                txtlongi.Text = pos.Coordinate.Longitude.ToString();
                txtAlti.Text = pos.Coordinate.Altitude.ToString();
                txtAccuracy.Text = pos.Coordinate.Accuracy.ToString();
                txtSpeed.Text = pos.Coordinate.Speed.ToString();
                txtTime.Text = pos.Coordinate.Timestamp.ToString();
                txtAltiAccu.Text = pos.Coordinate.AltitudeAccuracy.ToString();
                txtHeading.Text = pos.Coordinate.Heading.ToString();
                txtCity.Text = pos.CivicAddress.City.ToString();
                txtPostalCode.Text = pos.CivicAddress.PostalCode.ToString();
                txtState.Text = pos.CivicAddress.State.ToString();
                txtCountry.Text = pos.CivicAddress.Country.ToString();


            }
            catch (System.UnauthorizedAccessException)
            {

               
            }
            catch (TaskCanceledException)
            {
               
            }
            finally
            {
                _cts = null;
            }

                    }


        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.  The Parameter
        /// property is typically used to configure the page.</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }
    }
}
